/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package util.encrypt.apache_commons;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import org.apache.commons.io.IOUtils;

/**
 *
 * //http://stackoverflow.com/questions/10297825/encrypt-xml-file-in-net-and-decrypt-encrypted-file-in-java-using-x509-certificat
 * @author Rdelacruz
 */
public class CriptoRSA {
    public static byte[] rsaEncrypt(byte[] data, byte[] publicKey) throws IOException, InvalidKeySpecException,
                NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);

        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pk = kf.generatePublic(publicKeySpec);

        Cipher rsa = Cipher.getInstance("RSA");

        rsa.init(Cipher.ENCRYPT_MODE, pk);
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();

        CipherOutputStream os = new CipherOutputStream(byteOutputStream, rsa);
        os.write(data);
        os.flush();
        os.close();
        return byteOutputStream.toByteArray();
    }

    public static byte[] rsaDecrypt(byte[] data, byte[] privateKey) throws IOException, InvalidKeySpecException,
                NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKey);

        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey pk = kf.generatePrivate(privateKeySpec);

        Cipher rsa = Cipher.getInstance("RSA");

        rsa.init(Cipher.DECRYPT_MODE, pk);
        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(data);

        InputStream is = new CipherInputStream(byteInputStream, rsa);
        byte[] message = IOUtils.toByteArray(is);
        is.close();
        return message;
    }
}
